<template>
  <view class="content">
    <view class="user-info">
      <view class="avatar">
        <u-avatar :src="userInfo.avatar" size="100" @tap="show = true" />
      </view>
      <view class="info">
        <view class="name">{{ userInfo.nickName }}</view>
        <view class="id">用户ID:{{ userInfo.userId }}</view>
      </view>
    </view>

    <view class="menuList">
      <view class="menuItem" @click="jinFa" style="width: calc(100% / 3);">
        <u-icon :customStyle="{paddingTop:20+'rpx'}" name="/static/personal/shop.png" :size="50"></u-icon>
        <view style="font-size: 24rpx;margin-top: 10rpx;">京发云商城</view>
      </view>
      <view class="menuItem" @click="gotoPage('/pages/Personal/myLike')" style="width: calc(100% / 3);">
        <u-icon :customStyle="{paddingTop:20+'rpx'}" name="/static/personal/my_like.png" :size="50"></u-icon>
        <view style="font-size: 24rpx;margin-top: 10rpx;">我的喜欢</view>
      </view>
      <view class="menuItem" @click="gotoPage('/pages/Personal/records')" style="width: calc(100% / 3);">
        <u-icon :customStyle="{paddingTop:20+'rpx'}" name="/static/personal/follow.png" :size="50"></u-icon>
        <view style="font-size: 24rpx;margin-top: 10rpx;">我的追剧</view>
      </view>
    </view>

    <view class="navBox">
      <view class="navTitle">
        <view style="font-size: 32rpx;font-weight: 700;">福利钱包</view>
        <view style="display: flex;align-items: center;gap: 8rpx" @click="gotoPage('/pages/theater/withdrawal')">
          <u--image :showLoading="true" src="/static/personal/wallet.png" width="40rpx" height="40rpx"></u--image>
          <view style="color: #ffffff;font-size: 28rpx">提现</view>
        </view>
      </view>
      <view class="navBg">
        <view class="navBgLeft">
          <view class="navNum">{{userInfo.balance || 0}}</view>
          <view class="">金币余额</view>
        </view>
        <view class="navBgLeft">
          <view class="navNum">{{userInfo.money / 100 || 0}}</view>
          <view class="">现金余额</view>
        </view>
      </view>
    </view>

<!--    <view class="swiper" v-if="swiperList.length > 0">-->
<!--      <u-swiper :list="swiperList" @change="(e) => swiperCurrnet = e.current" keyName="image" @click="swiperClick" indicator indicatorMode="dot" indicatorActiveColor="#FE9E5A"-->
<!--                circular :autoplay='true' height='240'></u-swiper>-->
<!--    </view>-->

    <view class="followBox">
      <view class="followTitle" @click="gotoPage('/pages/Personal/records?current=1')">
        <view>浏览记录</view>
        <u-icon name="arrow-right" color="#8B8B8B" size="34"></u-icon>
      </view>
      <view class="follow">
        <view v-for="(item,index) in HistoryLis" :key="index" class="followItem" @click="gotoPage('/pages/player/player?tvId='+ item.tvId)">
          <u-image :src="item.tvImage" width="152.8rpx" height="190.2rpx" radius="16"></u-image>
          <view class="followItemTitle">{{item.tvName}}</view>
        </view>
      </view>
    </view>

    <view class="menuList">
      <view v-for="(listItem,listIndex) in menuList" :key="listIndex"  class="menuItem" @click="gotoPage('/pages/Personal/'+ listItem.url)">
        <u-icon
            :customStyle="{paddingTop:20+'rpx'}"
            :name="listItem.name"
            :size="50"
        ></u-icon>
        <view style="font-size: 24rpx;margin-top: 10rpx;">{{listItem.title}}</view>
      </view>
      <view class="menuItem" @click="openTop">
        <u-icon :customStyle="{paddingTop:20+'rpx'}" name="/static/personal/top.png" :size="50"></u-icon>
        <view style="font-size: 24rpx;margin-top: 10rpx;">填写邀请码</view>
      </view>
    </view>

    <u-popup :round="10" :show="show" @close="updateUserInfo">
      <view class="wrapper">
        <view class="header">编辑个人信息</view>
<!--        <view class="desc">获取用户头像、昵称等信息，主要用于向用户提供具有辨识度的用户中心界面</view>-->
        <view class="desc_avatar">
          <u-avatar :size="150" :src="userInfo.avatar" @click="chooseAvatarEvent" />
        </view>
        <view class="item">
          <view class="label">昵称</view>
          <input v-model="userInfo.nickName" class="input" placeholder="请输入昵称" placeholder-style="color: #AAAAAA;">
        </view>
        <view class="item" @click="showSex = true">
          <view class="label">性别</view>
          <input v-model="userInfo.sex" readonly :disabled="true" class="input" placeholder="请选择性别" placeholder-style="color: #AAAAAA;">
        </view>
        <view class="item" @click="showBirthday = true">
          <view class="label">生日</view>
          <input v-model="userInfo.birthdayTitle" readonly :disabled="true" class="input" placeholder="请填写生日" placeholder-style="color: #AAAAAA;">
        </view>
        <view class="item">
          <view class="label">签名</view>
          <input v-model="userInfo.signature" class="input" placeholder="介绍一下自己吧" placeholder-style="color: #AAAAAA;">
        </view>
      </view>
    </u-popup>

    <uni-popup ref="showTop" type="center" :mask-click="false" mode="center">
      <view class="top">
        <view class="topCenter">
          <view class="topTitle">填写邀请码</view>
          <input v-model="inviteCode" class="input" placeholder="请输入邀请码" placeholder-style="color: #AAAAAA;">
          <view class="btn" @click="inviteCodeClick">提交邀请码</view>
        </view>
        <u--image :showLoading="true" src="/static/personal/close.png" class="close" width="50rpx" height="50rpx" radius="24" @click="closeTop"></u--image>
      </view>
    </uni-popup>

    <u-picker :show="showSex" :columns="sexColumns"
              @close="showSex = false"
              :closeOnClickOverlay="true"
              :defaultIndex="userInfo.sex === '女' ? [1] : [0]"
              @cancel="showSex = false" itemHeight="60"
              confirmColor="#F73728" @confirm="sexConfirm"></u-picker>

    <u-datetime-picker :show="showBirthday"
                       v-model="userInfo.birthday"
                       mode="date" itemHeight="60"
                       @cancel="showBirthday = false"
                       confirmColor="#F73728"
                       :maxDate="new Date().getTime()"
                       :minDate="new Date(new Date().setFullYear(new Date().getFullYear() - 80)).getTime()"
                       :closeOnClickOverlay="true"
                       @close="showBirthday = false"
                       @confirm="birthdayConfirm"></u-datetime-picker>
  </view>
</template>

<script>
import {mapActions, mapMutations} from 'vuex'
import {Api} from '@/service/api'
import {gotoPage} from "../../utils/common";
import listItemVue from "../../components/listItem.vue";
import {getDateTime} from "../../utils/formatTime";

export default {
    components: {listItemVue},
		data() {
			return {
        userInfo: {
          userId: 0,
          avatar: null,
          nickName: '匿名用户',
          balance: 0,
          money: 0,
          sex: null,
          birthday: null,
          birthdayTitle: null,
          signature: null,
          inviteCode: null
        },
        HistoryLis: [],
        swiperList: [],
        swiperCurrnet: 0,
        show: false,
        menuList: [
          {
            name: '/static/personal/msg.png',
            title: '我的消息',
            url: 'msg'
          },
          {
            name: '/static/personal/invite.png',
            title: '邀请好友',
            url: 'invite'
          },
          {
            name: '/static/personal/like.png',
            title: '看剧喜好',
            url: 'like'
          },
          {
            name: '/static/personal/speed.png',
            title: '倍速设置',
            url: 'speed'
          },
          {
            name: '/static/personal/help.png',
            title: '帮助反馈',
            url: 'complaint'
          },
          {
            name: '/static/personal/service.png',
            title: '联系客服',
            url: 'qrcode'
          },
          {
            name: '/static/personal/set.png',
            title: '系统设置',
            url: 'set'
          },
          // {
          //   name: '/static/personal/download.png',
          //   title: '我的下载',
          //   url: 'download'
          // },
        ],
        showSex: false,
        showBirthday: false,
        sexColumns: [['男','女']],
        inviteCode: ''
			}
		},
    async onShow() {
      this.userInfo = await this.getInfoMethod()
      this.userInfo.sex = this.userInfo.sex === 0 ? '女' : '男'
      if(this.userInfo.birthday !== null) this.userInfo.birthdayTitle = getDateTime(new Date(this.userInfo.birthday))
      this.inviteCode = this.userInfo.inviteCode
      this.getHistoryList()
    },
    onLoad(){
      // this.swiper()
    },
		methods: {
      gotoPage,
      ...mapActions('userInfo', ['getInfoMethod']),
      ...mapMutations('userInfo', ['setInfoMethod']),
      async chooseAvatarEvent() {
        this.userInfo.avatar = await Api.upload()
      },
      async updateUserInfo() {
        await Api.updateUserInfo({
          avatar: this.userInfo.avatar,
          nickName: this.userInfo.nickName,
          sex: this.userInfo.sex === '男' ? 1 : 0,
          birthday: this.userInfo.birthday,
          signature: this.userInfo.signature,
        })
        this.show = false
        const {data} = await Api.refreshToken(this.userInfo.refreshToken)
        this.setInfoMethod(data)
      },
      getHistoryList(){
        Api.getHistoryList({
          pageNo: 1,
          pageSize: 4,
        }).then(res => {
          this.HistoryLis = res.data.list
        })
      },
      swiper(){
        Api.swiper().then(res=>{
          this.swiperList = res.data
        })
      },
      swiperClick(index) {
        let item = this.swiperList[index]
        uni.navigateToMiniProgram({
          appId: 'wx02417b7f6d0e32d0',
          path: "pages/index/index",
          success(res) {
            // 打开成功
            uni.showToast({
              title: '跳转成功'
            })
          },
          fail(err) {
            console.log(err)
            // 打开失败/取消
            uni.showToast({
              title: '跳转不成功'
            })
          }
        })
        // gotoPage(`/pages/player/player?tt_album_id=${item.albumId}&tt_episode_id=0&tvId=${item.tvId}`)
      },
      jinFa(){
        plus.share.getServices(function(res){
          let sweixin = null;
          for(let i=0; i<res.length; i++){
            const t = res[i];
            if(t.id == 'weixin'){
              sweixin = t;
            }
          }
          if(sweixin){
            // sweixin.launchMiniProgram({
            //   id: 'gh_657d490da83f',  //这里写你的小程序原始id（以gh开头）
            //   type: 0,//这里是不同的环境（默认0）
            //   path:'/pages/index/index'//这里是指定页的路径，如需传参直接字符串拼接（首页可以省略）
            // });

            sweixin.launchMiniProgram({
              id: 'gh_657d490da83f', //小程序原始ID
              path: 'pages/index/index',
              type: 0, //0 release ，1 test, 2 preview
              success: (res) => {
                console.log('成功')
              },
              fail: (res) => {
                console.log('失败')
              }
            })
          }
        },function(res){
          console.log(JSON.stringify(res));
        })
      },
      sexConfirm(val){
        const index = val.indexs[0]
        this.userInfo.sex = this.sexColumns[0][index]
        this.showSex = false
      },
      birthdayConfirm(val){
        const date = new Date(val.value);
        this.userInfo.birthdayTitle = getDateTime(date)
        this.userInfo.birthday = date
        this.showBirthday = false
      },
      openTop(){
        this.$refs.showTop.open('center')
      },
      async closeTop() {
        this.$refs.showTop.close()
        this.userInfo = await this.getInfoMethod()
      },
      async inviteCodeClick() {
        const user = await this.getInfoMethod()
        if(user.inviteCode !== null){
          uni.showToast({
            title: '已有邀请码，不可修改',
            icon: 'none',
          })
          return
        }
        if(!this.inviteCode || this.inviteCode.trim().length === 0){
          uni.showToast({
            title: '请输入邀请码',
            icon: 'none',
          })
          return
        }
        Api.updateUserInfo({
          inviteCode: this.inviteCode,
        }).then(async res => {
          const {data} = await Api.refreshToken(this.userInfo.refreshToken)
          this.setInfoMethod(data)
          this.$refs.showTop.close()
          uni.showToast({
            title: '保存成功',
            icon: 'none',
          })
        })
      }
		}
	}
</script>

<style>
page{
  background: url("/static/personal/my_bg.png") no-repeat;
  background-size: 100% 100%;
}
</style>

<style lang="scss" scoped>

.content{
  padding: 100rpx 30rpx 0;
  //height: 100vh;
}

.user-info {
  display: flex;
  width: 95%;
  // margin: auto;
  padding-bottom: 20rpx;
  // justify-content: space-between;
  align-items: center;
  padding-top: 40rpx;


  .info {
    margin-left: 20rpx;

    .id {
      font-size: 23rpx;
      color: #a5aaaa;
      padding-top: 15rpx;
    }
  }
}

.navBox {
  margin-top: 20rpx;
  width: calc(100% - 40rpx);
  height: 190rpx;
  color: #FFFFFF;
  border-radius: 20rpx;
  padding: 6rpx 18rpx;
  text-align: right;
  position: relative;
  background: url("/static/personal/wallet_bg.png") no-repeat;
  background-size: 100% 100%;

  .navTitle{
    display: flex;
    justify-content: space-between;
    color: #ffffff;
    margin: 15rpx 0 25rpx;
    padding: 0 20rpx;
  }

  .navBg {
    width: 100%;
    color: #ffffff;
    text-align: left;
    font-size: 24rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    float: left;
    position: relative;

    //&::after {
    //  content: '';
    //  width: 2rpx;
    //  height: 22rpx;
    //  position: absolute;
    //  left: 50%;
    //  top: 50%;
    //  transform: translate(-50%, -50%);
    //  background-color: #ABABAB;
    //}

    .navBgLeft{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .navNum {
        font-size: 40rpx;
        font-weight: 700;
      }
    }


  }
}

.followBox{
  background-color: #fff;
  margin-top: 30rpx;
  border-radius: 20rpx;
  padding: 20rpx;

  .followTitle{
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    font-size: 34rpx;
  }

  .follow {
    display: flex;
    gap: 10rpx;

    .followItem{
      display: flex;
      flex-direction: column;
      width: 152.8rpx;
      gap: 5rpx;

      .followItemTitle{
        font-size: 28rpx;
        width: 152.8rpx;
        display: -webkit-box;
        overflow: hidden;
        white-space: normal !important;
        text-overflow: ellipsis;
        word-wrap: break-word;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
  }
}

.swiper {
  width: 686rpx;
  height: 246rpx;
  border-radius: 20rpx;
  margin: 20rpx 0;
  overflow: hidden;
}

.menuList{
  background-color: #fff;
  border-radius: 20rpx;
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
  margin-top: 30rpx;

  .menuItem{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 170rpx;
    margin: 10rpx 0;
    background-color: #fff;
    font-size: 24rpx;

    &::after{
      border: none;
    }

  }
}

.wrapper {
  width: 100%;
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  padding: 60rpx 40rpx 40rpx;
  box-sizing: border-box;

  .item{
    width: 100%;
    margin-top: 16rpx;
    display: flex;
    align-items: center;

    .label{
      margin-right: 30rpx;
    }

    .input {
      width: 80%;
      background-color: #F8F7F8;
      padding: 20rpx 20rpx;
      border-radius: 30rpx;
    }
  }

  .header {
    font-size: 34rpx;
  }

  .desc {
    font-size: 26rpx;
    color: #AAAAAA;
    margin-top: 16rpx;
    padding-bottom: 30rpx;
  }

  .desc_avatar {
    width: 100%;
    margin: 30rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.top{
  width: 600rpx;
  height: 482rpx;
  position: relative;
  padding-top: 90rpx;

  .topCenter{
    width: 100%;
    height: 370rpx;
    background: url("/static/personal/topBg.png") no-repeat;
    background-size: 100% 100%;
    padding-top: 50rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .topTitle{
      font-size: 34rpx;
      font-weight: 700;
    }

    .input {
      width: 80%;
      background-color: #F3F3F3;
      padding: 20rpx 20rpx;
      border-radius: 30rpx;
      margin-top: 40rpx;
    }

    .btn{
      width: 530rpx;
      height: 88rpx;
      background-color: #E81F4B;
      color: #FFFFFF;
      text-align: center;
      line-height: 88rpx;
      border-radius: 208rpx;
      margin: 46rpx auto 0;
    }
  }

  .close{
    position: absolute;
    top: 0;
    right: 0;
  }
}
</style>
